package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import com.itheima.util.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.rmi.MarshalledObject;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据报表
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetMealService setMealService;
    @Reference
    private ReportService reportService;

    //会员数量折线图
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        /*//模拟数据测试对象格式看数据是否是echarts所需的格式
        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        list.add("2019.01");
        list.add("2019.02");
        list.add("2019.03");
        list.add("2019.04");
        list.add("2019.05");
        map.put("months", list);
        List<Integer> list2 = new ArrayList<>();
        list2.add(50);
        list2.add(70);
        list2.add(100);
        list2.add(200);
        list2.add(180);
        map.put("memberCount", list2);*/

        Calendar calendar = Calendar.getInstance();//获得日历对象，模拟时间就是当前时间
        calendar.add(Calendar.MONTH, -12);//获得当前时间往前推一年的时间
        int num=12;
        Map map = getMap(calendar, num);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }
    //会员数量饼图

    @RequestMapping("/getMemberReportByAges")
    public Result getMemberReportByAges() {
        Map<String, Object> map = new HashMap<>();
        try {
            List<String> memberAges = new ArrayList<>();
            List<Map<String,Object>> list = memberService.findMemberCountByAges ();
            for (Map<String, Object> stringObjectMap : list) {
                String name = (String) stringObjectMap.get ( "name" );
                System.out.println (name);
                memberAges.add ( name );
            }
            map.put("memberCount", list);
            map.put ( "memberAges" ,memberAges);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }






    @RequestMapping("/getMemberReportByAge")
    public Result getMemberReportByAge() {
        Map<String, Object> map = new HashMap<>();
        //封装时间
        List<Map<String,String>> ages = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();//获得日历对象，模拟时间就是当前时间
        Date time0 = calendar.getTime ();
        String age0 = new SimpleDateFormat("yyyy.MM.dd").format(time0);
        calendar.add(Calendar.YEAR,-18);//获得当前时间往前推18年的时间
        Date time1 = calendar.getTime ();
        String age1 = new SimpleDateFormat("yyyy.MM.dd").format(time1);
        Map<String, String> year1 = new HashMap<>();
        year1.put ( "now",age0 );
        year1.put ( "before",age1 );
        ages.add(year1);
        calendar.add(Calendar.YEAR,-30);//获得当前时间往前推30年的时间
        Date time2 = calendar.getTime ();
        String age2 = new SimpleDateFormat("yyyy.MM.dd").format(time2);
        Map<String, String> year2 = new HashMap<>();
        year2.put ( "now",age1 );
        year2.put ( "before",age2 );
        ages.add(year2);
        calendar.add(Calendar.YEAR,-45);//获得当前时间往前推45年的时间
        Date time3 = calendar.getTime ();
        String age3 = new SimpleDateFormat("yyyy.MM.dd").format(time3);
        Map<String, String> year3 = new HashMap<>();
        year3.put ( "now",age2 );
        year3.put ( "before",age3 );
        ages.add(year3);
        calendar.add(Calendar.YEAR,-150);//获得当前时间往前推45年的时间
        Date time4 = calendar.getTime ();
        String age4 = new SimpleDateFormat("yyyy.MM.dd").format(time4);
        Map<String, String> year4 = new HashMap<>();
        year4.put ( "now",age3 );
        year4.put ( "before",age4 );
        ages.add(year4);
        try {
            List<String> memberAges = new ArrayList<>();
            List<Map<String,Object>> list = memberService.findMemberCountByYears(ages);
            for (Map<String, Object> stringObjectMap : list) {
                String name = (String) stringObjectMap.get ( "name" );
                System.out.println (name);
                memberAges.add ( name );
            }
            map.put("memberCount", list);
            map.put ( "memberAges" ,memberAges);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }
    //    套餐预约占比饼形图
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        List<Map<String, Object>> list = setMealService.getSetmealCount();
        Map<String, Object> map = new HashMap<>();
        map.put("setmealCount", list);
        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : list) {
            String name = (String) stringObjectMap.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }
    @RequestMapping("/getMemberReportBySex")
    public Result getMemberReportBySex() {
        try {
            List<Map<String, Object>> list= memberService.findMemberCountBySex ();
            Map<String, Object> map = new HashMap<>();
            List<String> memberSex = new ArrayList<>();
            map.put ( "memberCount", list);
            for (Map<String, Object> stringObjectMap : list) {
                String name = (String) stringObjectMap.get ( "name" );
                memberSex.add(name);
            }
            map.put ( "memberSex",memberSex );
            return new Result ( true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map );
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result ( false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL );
        }

    }
   //获得运营数据
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            //远程调用报表服务获得报表数据
            Map<String, Object> map = reportService.getBusinessReportData();
            String reportDate = (String) map.get("reportDate");//当前日期 reportDate
            Integer todayNewMember = (Integer) map.get("todayNewMember");//今日新增会员数 todayNewMember
            Integer totalMember = (Integer) map.get("totalMember");//总会员数 totalMember
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");//本周新增会员数 thisWeekNewMember
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");//本月新增会员数 thisMonthNewMember
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");//今日预约数 todayOrderNumber
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");//今日到诊数 todayVisitsNumber
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");//本周预约数 thisWeekOrderNumber
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");//本周到诊数 thisWeekVisitsNumber
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");//本月预约数 thisMonthOrderNumber
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");//本月到诊数 thisMonthVisitsNumber
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");//热门套餐 hotSetmeal
            //动态获取这个表格文件在该项目中的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //基于模板文件来创建一个excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//当前日期
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//今日新增会员数
            row.getCell(7).setCellValue(totalMember);//总会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            //热门套餐
            for (Map map1 : hotSetmeal) {
                String name = (String) map1.get("name");
                Long setmeal_count = (Long) map1.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map1.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }
            //使用输出流进行表格下载，基于浏览器作为客户端进行下载
            ServletOutputStream out = response.getOutputStream();
            //告诉浏览器输出的文件是什么类型的
            response.setContentType("application/vnd.ms-excel");//代表的是excel类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式下载
            excel.write(out);
            out.flush();//刷新一下输出流
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据pdf格式
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response){
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");
            //动态获取模板文件的磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business3.jasper";
            //编译模板，编译后为后缀是jasper的二进制文件
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            //填充数据--使用javabean数据源的方式填充
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, map, new JRBeanCollectionDataSource(hotSetmeal));
            //使用输出流进行pdf文件下载，基于浏览器作为客户端进行下载
            ServletOutputStream out = response.getOutputStream();
            //告诉浏览器输出的文件是什么类型的
            response.setContentType("application/pdf");//代表是pdf格式
            response.setHeader("content-Disposition","attachment;filename=report.pdf");//指定以附件形式下载
            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    @RequestMapping("/getMemberReportByDate")
    public Result getMemberReportByDate(@RequestBody Map map1) {

        try {
            String startDate = (String) map1.get("startDate");
            String endDate = (String) map1.get("endDate");
            Integer startYear = getYear(startDate);
            Integer startMonth = getMonth(startDate);
            Integer endYear = getYear(endDate);
            Integer endMonth = getMonth(endDate);
            int num_year=endYear-startYear;
            int num_month=endMonth-startMonth;
            int num=num_year*12+num_month+1;
            Calendar calendar = getCalendar(startDate);
            calendar.add(Calendar.MONTH,-1);
            Map map = getMap(calendar, num);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }


//        memberService.findMemberCountByMonths()
    }
    public Map getMap(Calendar calendar,int num){
        List<String> months = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < num; i++) {
            calendar.add(Calendar.MONTH, 1);//每遍历一次往后推一个月
            Date time = calendar.getTime();
            String month = new SimpleDateFormat("yyyy.MM").format(time);
            months.add(month);
        }
        map.put("months", months);
        List<Integer> count = memberService.findMemberCountByMonths(months);
        map.put("memberCount", count);
        return map;
    }

    public Integer getYear(String date)throws Exception{
        Calendar calendar = getCalendar(date);
        int year = calendar.get(Calendar.YEAR);
        return year;
    }
    public Integer getMonth(String date)throws Exception{
        Calendar calendar = getCalendar(date);
        int month = calendar.get(Calendar.MONTH);
        return month;
    }
    public Calendar getCalendar(String date) throws Exception{
        Date d = DateUtils.parseString2Date(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.DATE,+1);
        return calendar;
    }

}
